package com.seisys.service.system.user;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.seisys.dao.DaoSupport;
import com.seisys.dto.CheckAuthRequest;
import com.seisys.dto.CheckAuthResponse;
import com.seisys.entity.Page;
import com.seisys.entity.system.User;
import com.seisys.exception.ExceptionUtil;
import com.seisys.exception.ServiceException;
import com.seisys.exception.ValidateException;
import com.seisys.user.constants.ResponseCodeEnum;
import com.seisys.util.IData;
import com.seisys.util.JwtTokenUtils;
import com.seisys.util.PageData;


@Service("userService")
public class UserService
{

	Logger Log=LoggerFactory.getLogger(this.getClass());
	
    @Resource(name = "daoSupport")
    private DaoSupport dao;

    // ======================================================================================

    /*
     * 通过id获取数据
     */
    public PageData findByUiId(PageData pd)
        throws Exception
    {
        return (PageData)dao.findForObject("UserXMapper.findByUiId", pd);
    }

    /**
     * Description: (必填) 1、获取用户系统角色 2、用于编辑框回显
     * 
     * @param pd
     * @return
     * @throws Exception
     * @see
     */
    @SuppressWarnings("unchecked")
    public List<PageData> findUserSysRoleByUiId(PageData pd)
        throws Exception
    {
        return (List<PageData>)dao.findForList("UserXMapper.findUserSysRoleByUiId", pd);
    }

    /*
     * 通过loginname获取数据
     */
    public PageData findByUId(PageData pd)
        throws Exception
    {
        return (PageData)dao.findForObject("UserXMapper.findByUId", pd);
    }

    /*
     * 通过邮箱获取数据
     */
    public PageData findByUE(PageData pd)
        throws Exception
    {
        return (PageData)dao.findForObject("UserXMapper.findByUE", pd);
    }

    /*
     * 通过编号获取数据
     */
    public PageData findByUN(PageData pd)
        throws Exception
    {
        return (PageData)dao.findForObject("UserXMapper.findByUN", pd);
    }

    /**
     * Description: (必填) 1、新增用户 2、新增用户系统角色
     * 
     * @param param
     * @throws Exception
     * @see
     */
    @SuppressWarnings("unchecked")
    @Transactional
    public void saveU(PageData param)
        throws Exception
    {
        dao.save("UserXMapper.saveU", param);
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> mapList = (List<Map<String, Object>>)param.get("mapList");
        for (Map<String, Object> map : mapList)
        {
            if (!"".equals(map.get("roleId")))
            {
                list.add(map);
            }
        }
        if (list.size() != 0)
        {
            param.put("mapList", list);
            dao.save("UserXMapper.insertUserSysRole", param);
        }

    }

    /**
     * Description: (必填) 1、修改用户 2、删除用户系统角色信息，新增用户系统角色信息
     * 
     * @param pd
     * @throws Exception
     * @see
     */
    @SuppressWarnings("unchecked")
    public void editU(PageData pd)
        throws Exception
    {
        dao.update("UserXMapper.editU", pd);

        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> mapList = (List<Map<String, Object>>)pd.get("mapList");
        if(mapList != null)
        {
        	dao.delete("UserXMapper.delUserSysRole", pd);
        	for (Map<String, Object> map : mapList)
            {
                if (!"".equals(map.get("roleId")))
                {
                    list.add(map);
                }
            }
        }
        if (list.size() != 0)
        {
            pd.put("mapList", list);
            dao.save("UserXMapper.insertUserSysRole", pd);
        }
    }

    /*
     * 修改用户密码
     */
    public void editPwd(PageData pd)
        throws Exception
    {
        dao.update("UserXMapper.editPwd", pd);
    }

    /*
     * 删除用户
     */
    public void deleteU(PageData pd)
        throws Exception
    {
        dao.update("UserXMapper.updateU", pd);// 逻辑删除，更改del_flag为1
    }

    /*
     * 批量删除用户
     */
    public void deleteAllU(String[] USER_IDS)
        throws Exception
    {
        dao.update("UserXMapper.updateAllU", USER_IDS);

    }

    /*
     * 用户列表(用户组)
     */
    public List<PageData> listPdPageUser(Page page)
        throws Exception
    {
        return (List<PageData>)dao.findForList("UserXMapper.userlistPage", page);
    }

    /*
     * 用户列表(用户组)
     */
    @SuppressWarnings("unchecked")
    public List<User> listMapUser(Map<String, Object> param)
        throws Exception
    {
        return (List<User>)dao.findForList("UserXMapper.userlistMap", param);
    }

    public Integer countMapUser()
        throws Exception
    {
        return (Integer)dao.findForObject("UserXMapper.countMapUser", null);
    }

    public Integer countSearchUser(Map<String, Object> param)
        throws Exception
    {
        return (Integer)dao.findForObject("UserXMapper.countSearchUser", param);
    }

    /*
     * 用户列表(全部)
     */
    public List<PageData> listAllUser(PageData pd)
        throws Exception
    {
        return (List<PageData>)dao.findForList("UserXMapper.listAllUser", pd);
    }

    /*
     * 用户列表(供应商用户)
     */
    public List<PageData> listGPdPageUser(Page page)
        throws Exception
    {
        return (List<PageData>)dao.findForList("UserXMapper.userGlistPage", page);
    }

    /*
     * 保存用户IP
     */
    public void saveIP(PageData pd)
        throws Exception
    {
        dao.update("UserXMapper.saveIP", pd);
    }

    /*
     * 登录判断（jwt）
     */
    public PageData getUserByNameAndPwd(PageData pd)
        throws Exception
    {
    	PageData returnPD = new PageData();
    	try{
    		beforeValidate(pd);
    		returnPD = (PageData)dao.findForObject("UserXMapper.getUserInfo", pd);
    		if(null == returnPD){
//    			returnPD.put("code", ResponseCodeEnum.USERORPASSWORD_ERRROR.getCode());
//    			returnPD.put("msg", ResponseCodeEnum.USERORPASSWORD_ERRROR.getMsg());
    			return returnPD;
    		}
    		Map<String,Object> map=new HashMap<>();
            map.put("uid",returnPD.get("USER_ID").toString());
//            map.put("exp",4000);
            map.put("exp",DateTime.now().plusDays(1).toDate().getTime()/1000);
            
            returnPD.put("token", JwtTokenUtils.generatorToken(map));
            
            Claims claims = JwtTokenUtils.phaseToken(JwtTokenUtils.generatorToken(map));
            
            returnPD.put("uid", returnPD.get("USER_ID"));
            returnPD.put("code",ResponseCodeEnum.SUCCESS.getCode());
            returnPD.put("msg",ResponseCodeEnum.SUCCESS.getMsg());
    	}catch(Exception e){
    		Log.error("login occur exception :"+e);
            ServiceException serviceException=(ServiceException) ExceptionUtil.handlerException4biz(e);
            returnPD.put("code",serviceException.getErrorCode());
            returnPD.put("msg",serviceException.getErrorMessage());
    	}finally{
    		Log.info("login response->"+returnPD);
    	}
        return returnPD;
    }

    /*
     * 跟新登录时间
     */
    public void updateLastLogin(PageData pd)
        throws Exception
    {
        dao.update("UserXMapper.updateLastLogin", pd);
    }

    /*
     * 通过id获取数据
     */
    public User getUserAndRoleById(String USER_ID)
        throws Exception
    {
        return (User)dao.findForObject("UserMapper.getUserAndRoleById", USER_ID);
    }
    
    public User getUserAndRoleByIdNew(String USER_ID)
            throws Exception
        {
            return (User)dao.findForObject("UserMapper.getUserAndRoleByIdNew", USER_ID);
        }

    /**
     * demo_liuwei
     * 
     * @param param
     * @return
     */
    public List<User> listAllUserbyTable(Map<String, Object> param)
    {
        return (List<User>)dao.listAllUserBytable("UserMapper.listAllUserByTable", param);
    }

    @SuppressWarnings("unchecked")
    public List<IData> listTreeData()
        throws Exception
    {
        return (List<IData>)dao.findForList("UserXMapper.listTreeData", null);
    }

    @SuppressWarnings("unchecked")
    public List<IData> listMenuId(IData param)
        throws Exception
    {
        return (List<IData>)dao.findForList("UserXMapper.listMenuId", param);
    }

    public void deleteSubSys(IData param)
        throws Exception
    {
        dao.delete("UserXMapper.deleteSubSys", param);
    }

    public void insertSubSys(IData param)
        throws Exception
    {
        dao.save("UserXMapper.insertSubSys", param);
    }

    /**
     * Description: (必填) 1、获取当前用户下能进的子系统和角色
     * 
     * @return
     * @throws Exception
     * @see
     */
    @SuppressWarnings("unchecked")
    public List<IData> showusermenurole(IData param)
        throws Exception
    {
        return (List<IData>)dao.findForList("UserXMapper.showusermenurole", param);
    }

    /**
     * Description: (必填) 1、查询子系统名字和id
     * 
     * @return
     * @throws Exception
     * @see
     */
    @SuppressWarnings("unchecked")
    public List<IData> showSubSystem()
        throws Exception
    {
        return (List<IData>)dao.findForList("UserXMapper.showSubSystem", null);
    }

    /**
     * Description: (必填) 1、恢复用户
     * 
     * @param param
     * @see
     */
    public void revertUser(IData param)
        throws Exception
    {
        dao.update("UserXMapper.revertUser", param);
    }
    
    public CheckAuthResponse validToken(CheckAuthRequest request){
    	CheckAuthResponse response = new CheckAuthResponse();
    	try{
    		beforeValidateAuth(request);
    		
    		Claims claims = JwtTokenUtils.phaseToken(request.getToken());
    		response.setUid(claims.get("uid").toString());
    		response.setCode(ResponseCodeEnum.SUCCESS.getCode());
    		response.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
    	}catch (ExpiredJwtException e){
            Log.error("Expire :"+e);
            response.setCode(ResponseCodeEnum.TOKEN_EXPIRE.getCode());
            response.setMsg(ResponseCodeEnum.TOKEN_EXPIRE.getMsg());
        }catch (SignatureException e1){
            Log.error("SignatureException :"+e1);
            response.setCode(ResponseCodeEnum.SIGNATURE_ERROR.getCode());
            response.setMsg(ResponseCodeEnum.SIGNATURE_ERROR.getMsg());
        }catch (Exception e){
            Log.error("login occur exception :"+e);
            ServiceException serviceException=(ServiceException) ExceptionUtil.handlerException4biz(e);
            response.setCode(serviceException.getErrorCode());
            response.setMsg(serviceException.getErrorMessage());
        }finally{
    		Log.info("reponse:"+response);
    	}
    	
    	
    	return response;
    }
    
    
    private void beforeValidate(PageData pd){
    	if(pd == null){
    		 throw new ValidateException("请求对象为空");
    	}
    	if(StringUtils.isEmpty(pd.get("USERNAME"))){
            throw new ValidateException("用户名为空");
        }
        if(StringUtils.isEmpty(pd.get("PASSWORD"))){
            throw new ValidateException("密码为空");
        }
    }
    
    private void beforeValidateAuth(CheckAuthRequest request){
        if(request==null){
            throw new ValidateException("请求对象为空");
        }
        if(StringUtils.isEmpty(request.getToken())){
            throw new ValidateException("token信息为空");
        }
    }

	public List<User> findUserListMap(Page pg) throws Exception {
		return (List<User>)dao.findForList("UserXMapper.findUserListMap", pg);
	}

	public PageData findByUserId(PageData pd) throws Exception {
		return (PageData)dao.findForObject("UserXMapper.findByUserId", pd);
	}

	public int cleanUserToken(User user) throws Exception {
		return (int)dao.update("UserXMapper.cleanUserToken", user);
	}

	public User getUserRoleById(String USER_ID) throws Exception {
		return (User)dao.findForObject("UserMapper.getUserRoleById", USER_ID);
	}

}
